package com.snacks;

import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.sax.Element;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.snacks.data.DataFromHttpSever;
import com.snacks.data.URLconstan;
import com.snacks.map.XMLParser;

public class Main extends Activity {

	static final String ID = "id";
	static final String NAME = "name";
	static final String ADDRESS = "address";
	static final String CREATE_USER = "createuser";
	static final String CREATE_DATE = "createdate";
	static final String PHONE_NUMBER = "phonenumber";
	static final String THUMBNAIL = "thumbnail";
	private boolean isLoadMore;
	ListView listView;
	customAdapter adapter;
	Toast toast;
	
	public ArrayList<HashMap<String, String>> mylist;
	public ArrayList<HashMap<String, String>> bufferList;
	
	private boolean isLoadingData = true;
	private int indexPage = 1;
	private int totalpage = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		toast = Toast.makeText(Main.this, "Đang kết nối ...", Toast.LENGTH_SHORT);
		toast.show();
		
		mylist = new ArrayList<HashMap<String, String>>();
		bufferList = new ArrayList<HashMap<String, String>>();

		listView = (ListView) findViewById(R.id.mainlist);

		adapter = new customAdapter(this, mylist);
		listView.setAdapter(adapter);

		// when click items
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				HashMap<String, String> hashmap = new HashMap<String, String>();
				hashmap = mylist.get(position);
				Intent intent = new Intent(getBaseContext(), ItemDetail.class);
				intent.putExtra("restaurant", hashmap);
				startActivity(intent);
			}
		});
		listView.setOnScrollListener(new AbsListView.OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (listView.getLastVisiblePosition() +1 >= totalItemCount) {					
					loadMoreData();
				}
				// TODO Auto-generated method stub
				Log.d("Loaddata",totalItemCount + " -------- Item : " + listView.getLastVisiblePosition());
			}
		});
		
		loadData();
	}
	
	public void loadMoreData() {
		if (isLoadingData || indexPage >= totalpage) {
			return;
		}
		Toast.makeText(Main.this, "Loading ...", Toast.LENGTH_LONG).show();	
		
		indexPage++;
		loadData();
	}

	private void loadData() {

		new processLoadMore().execute();
	}

	final Handler addImagelist = new Handler() {
		public void handleMessage(Message msg) {
			try {
				toast.cancel();
				mylist.addAll(bufferList);
				adapter.notifyDataSetChanged();
				Log.d("LoadData", "Them thanh cong : " + mylist.size());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	public class processLoadMore extends AsyncTask<Void, Boolean, Boolean> {

		@Override
		protected void onPostExecute(Boolean result) {

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();

		}

		protected void onResume() {
		}

		@Override
		protected Boolean doInBackground(Void... arg0) {
			try {
				bufferList.clear();
				// Log.e("", "-- : " + URL + indexPage);
				isLoadingData = true;
				
				// parse json data
				
				ArrayList<NameValuePair> rq = new ArrayList<NameValuePair>();
				DataFromHttpSever dt = new DataFromHttpSever();
				String result = "";
				
				rq.add(new BasicNameValuePair("page", Integer.toString(indexPage)));				
				
				result = dt.getDataFromHttpSever(rq, URLconstan.getTopItemService());	

				try {
					JSONArray jArray = new JSONArray(result);	
					Log.i("log_tag", "Data Length: " + jArray.length());
					for (int i = 0; i < jArray.length(); i++) {

						HashMap<String, String> map = new HashMap<String, String>();
						JSONObject e = jArray.getJSONObject(i);

						Log.i("log_tag", "Name: " + e.getString("name") + ", address: " + e.getString("address"));

						map.put(ID, e.getString("id"));
						map.put(NAME, e.getString("name"));
						map.put(ADDRESS,"Địa chỉ:" + e.getString("address") + ", " + e.getString("area"));
						map.put(PHONE_NUMBER, "Mobile: " + e.getString("phonenumber"));
						map.put(THUMBNAIL,URLconstan.getServer() + "/uploads/" + e.getString("thumbnail"));
						map.put(CREATE_USER, "Người Đăng: " + e.getString("createuser"));
						map.put(CREATE_DATE, "Ngày Đăng: " + e.getString("createdate"));
						bufferList.add(map);
						totalpage = Integer.parseInt(e.getString("total"));
					}
					
					Log.i("log_tag", "page: " + indexPage + ", total: " + totalpage);
					
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString());
				}
				
				isLoadingData = false;
				addImagelist.sendEmptyMessage(0);
			} catch (Exception e) {
				disconnect.sendEmptyMessage(0);
			}
			return true;
		}
	}

	final Handler disconnect = new Handler() {
		public void handleMessage(Message msg) {
			toast = Toast.makeText(Main.this,
							"Rất tiếc không thể kết nối tới máy chủ. Xin vui lòng kiểm tra kết nối mạng.",
							Toast.LENGTH_LONG);
			toast.show();
		}
	};

}
